package com.zpeb.pdd.controller;

import com.zpeb.pdd.entity.User;
import com.zpeb.pdd.service.UserInfo;
import com.zpeb.pdd.utils.MD5;
import com.zpeb.pdd.utils.Msg;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author VX5
 * @Title: MJC
 * @ProjectName pdd
 * @Description: TODO
 * @date ${DAT}11:54
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    UserInfo userInfo;
    @Autowired
    StringRedisTemplate redisTemplate;

    private Logger log =  LoggerFactory.getLogger(LoginController.class);
    /**
     * 登录
     * @param map
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping
    public Msg login(@RequestBody Map<String,String> map, HttpServletRequest request) throws Exception {
        //指定redis初始的库
//        JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) redisTemplate.getConnectionFactory();
//        redisTemplate.setConnectionFactory(jedisConnectionFactory);


        String userName = map.get("username");
        String passWord = map.get("password");
        //判断是否输入为空
        if (userName == null || userName.equals("")){
            return Msg.loginFail().add("msg","用户名不能为空");
        }
        if (passWord == null || passWord.equals("")){
            return Msg.loginFail().add("msg","密码不能为空");
        }
        User user = userInfo.getPasswordByUsername(userName);
        if (!user.getPassword().equals(MD5.md5Encode(passWord))){
            return Msg.loginFail().add("msg","密码错误");
        }else {
            //创建token
            String token = MD5.md5Encode(user.getUsername());
            Map<String,String> map1 = new HashMap<>();
            map1.put("username",user.getUsername());
            map1.put("role",user.getRole());
            map1.put("userid",user.getUserid());
            map1.put("token",token);
            // 将token存入redis并且设置一天的过期时间
            redisTemplate.opsForValue().set(token,user.getUsername(),1,TimeUnit.DAYS);
            Long time = redisTemplate.getExpire(token, TimeUnit.MINUTES);
            log.info("成功存储token，有效期"+time+"min");
            return Msg.success().add("msg",map1);
        }
    }


    /**
     * 注册
     * @param user
     * @return
     * @throws Exception
     */
    @PostMapping("/register")
    public Msg addUser(@RequestBody  User user) throws Exception {
        int result = userInfo.addUser(user);
        if (result == 0) {
            return Msg.fail().add("msg", "请输入必要信息");
        } else {
            return Msg.success().add("msg", "成功注册" + result + "条信息");
        }
    }
}
